package com.financing.wap.web.controller.api;


import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;




import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.financing.mail.service.MailSenderService;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.common.Session;
import com.financing.wap.dto.AuthenticationDTO;
import com.financing.wap.dto.CertDTO;
import com.financing.wap.dto.MessageMailDTO;
import com.financing.wap.dto.MessageSmsDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IAuthenticationService;
import com.financing.wap.service.IMessageService;
import com.financing.wap.util.DateUtil;
import com.financing.wap.util.MessageUtil;
import com.financing.wap.util.PropertiesUtils;
import com.financing.wap.web.controller.BaseController;



/**
 * FA身份认证Controller
 * @author hetaihe
 *
 */
@Controller("apiFaAuthenticationController")
@RequestMapping(value="/api/authentication")
public class FaAuthenticationController extends BaseController {
	
	Logger logger = Logger.getLogger(getClass());

	@Autowired
	public IAuthenticationService authenticationService;


	@Autowired
	private MailSenderService mailSenderService;
	
	@Autowired
	public IMessageService messageService;

	@RequestMapping(value="/submit", method=RequestMethod.GET)
	@ResponseBody
	public ResultMap input(HttpServletRequest request,AuthenticationDTO auth, BindingResult br){

		ResultMap result = new ResultMap();
		UserDTO user = super.getSession().getUser();
		try{
			if(br.hasErrors()){
				log.error("FA authentication error : "+br.getFieldError().getDefaultMessage());
				result.setStatus(ResultMap.STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_VALIDATE_ERROR);
				result.setMessage("提交数据校验失败，数据部合法");
				return result;
			}
			String certStr = request.getParameter("certjson");
			List<CertDTO> certList =JSON.parseArray(certStr, CertDTO.class);
			
			auth.setCert(certList);
			auth.setFaId(user.getId());
			authenticationService.submitAuthInfo(auth);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setMessage("FA资料提交成功，等待审核");

			log.info("start send Message！");
			//短信及邮件验证
			Map<String,Object> params = new HashMap<String,Object>();
//			注册用户【{uName}】已于【{time}】
			params.put("uName", user.getLoginName());
			params.put("time", DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
			sendMessageAndMail(params);
			log.info("start send Message  success！");
		}catch(Exception e){
			log.warn("==>warn messang:",e);
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			result.setMessage("系统异常");
		}

		return result;
	}

	@RequestMapping(value="/queryAuth", method=RequestMethod.GET)
	@ResponseBody
	public ResultMap queryAuth(){

		ResultMap result = new ResultMap();

		Session session = super.getSession();
		UserDTO user = session.getUser();
		try{
			AuthenticationDTO auth = authenticationService.queryAuthInfo(user.getId());
			result.setAttribute("auth", auth);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setMessage("FA资料信息查询成功");
		}catch(Exception e){
			logger.error("==Error message=>"+e.getMessage());
			result.setAttribute("auth", new AuthenticationDTO());
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setMessage("FA资料信息查询失败");
		}
		
		return result;
	}

	/**
	 * 消息和邮件发送
	 * @param params
	 */
	private  void sendMessageAndMail(Map<String,Object> params){
		String otpMobile=PropertiesUtils.getValue("op_mobile");
		String mailSenter=PropertiesUtils.getValue("op_mail");
		Map<String,Object> m  = MessageUtil.getMessage("messageAndMail","faAuthentication",params);
		String title = (String)m.get(MessageUtil.KEY_TITLE);
		String content = (String)m.get(MessageUtil.KEY_CONTENT);
		//邮件发送
//		logger.info("start send mail");
//		MailContentDTO mail = new MailContentDTO();
		//mail.setCc("op@superfa.cn");
//		mail.setContext(content);
//		mail.setRecAddress("op@superfa.cn");
//		mail.setSubject(title);
//		mail.setRequestTime(new Date());
//		mailSenderService.send(mail);
//		logger.info("start send otp");
		//		sendOtpMessage("",content);
//		smsService.sendOtpMessage(otpMessage, content);
		MessageMailDTO mail = new MessageMailDTO();
		mail.setFpMailContent(content);
		mail.setFpMailTitle(title);
		mail.setFpMailTo(mailSenter);
		messageService.insertMailInfo(mail);
		
		MessageSmsDTO messageSmsDTO = new MessageSmsDTO();
		messageSmsDTO.setFpSmsContent(content);
		messageSmsDTO.setFpSmsRecivePhoneNo(otpMobile);
		messageService.addMessageSms(messageSmsDTO);
	}

	public static void main(String[] orgs){
		String xx = "[{\"certType\":\"01\",\"certNo\":\"111111\"},{\"certType\":\"03\",\"certNo\":\"3333\"}]";
		List<CertDTO> l  = JSON.parseArray(xx, CertDTO.class);
		System.out.println("===>"+l.size());
	}
}
